package com.yjc.rabbitmq.springboot_rabbitmq.config;

import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @author shkstart
 * @create 2022-08-02 16:34
 */
@Configuration
public class TTLQueueConfig {

    //死信队列名
    private static final String D_DEAD_LETTER_QUEUE_NAME = "QD";
    //死信交换机名
    private static final String Y_DEAD_LETTER_EXCHANGE_NAME = "Y";
    //普通队列名
    private static final String A_QUEUE_NAME = "QA";
    private static final String B_QUEUE_NAME = "QB";
    private static final String C_QUEUE_NAME = "QC";
    //普通交换机名
    private static final String X_EXCHANGE_NAME = "X";

    @Bean("XExchange")
    public DirectExchange XExchange() {
        return new DirectExchange(X_EXCHANGE_NAME);
    }

    @Bean("YDeadLetterExchange")
    public DirectExchange YDeadLetterExchange() {
        return new DirectExchange(Y_DEAD_LETTER_EXCHANGE_NAME);
    }

    @Bean("queueA")
    public Queue queueA() {
        Map<String, Object> arguments = new HashMap<>();
        arguments.put("x-message-ttl", 10000);
        arguments.put("x-dead-letter-exchange", Y_DEAD_LETTER_EXCHANGE_NAME);
        arguments.put("x-dead-letter-routing-key", "YD");
        return QueueBuilder.durable(A_QUEUE_NAME).withArguments(arguments).build();
    }

    @Bean("queueB")
    public Queue queueB() {
        Map<String, Object> arguments = new HashMap<>();
        arguments.put("x-message-ttl", 40000);
        arguments.put("x-dead-letter-exchange", Y_DEAD_LETTER_EXCHANGE_NAME);
        arguments.put("x-dead-letter-routing-key", "YD");
        return QueueBuilder.durable(B_QUEUE_NAME).withArguments(arguments).build();
    }

    @Bean("queueC")
    public Queue queueC() {
        Map<String, Object> arguments = new HashMap<>();
        arguments.put("x-dead-letter-exchange", Y_DEAD_LETTER_EXCHANGE_NAME);
        arguments.put("x-dead-letter-routing-key", "YD");
        return QueueBuilder.durable(C_QUEUE_NAME).withArguments(arguments).build();
    }

    @Bean("queueD")
    public Queue queueD() {
        return QueueBuilder.durable(D_DEAD_LETTER_QUEUE_NAME).build();
    }

    @Bean
    public Binding queueABindingXExchange(Queue queueA, DirectExchange XExchange) {
        return BindingBuilder.bind(queueA).to(XExchange).with("XA");
    }

    @Bean
    public Binding queueBBindingXExchange(Queue queueB, DirectExchange XExchange) {
        return BindingBuilder.bind(queueB).to(XExchange).with("XB");
    }

    @Bean
    public Binding queueCBindingXExchange(Queue queueC, DirectExchange XExchange) {
        return BindingBuilder.bind(queueC).to(XExchange).with("XC");
    }

    @Bean
    public Binding queueDBindingYExchange(Queue queueD, DirectExchange YDeadLetterExchange) {
        return BindingBuilder.bind(queueD).to(YDeadLetterExchange).with("YD");
    }
}
